package com.hiyee.api.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiyee.annotation.CurrentCustomer;
import com.hiyee.pojo.auth.CustomerTokenInfo;
import com.hiyee.pojo.auth.LoginCustomer;
import com.hiyee.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前客户的登录信息
 *
 * @author WangBin
 */
@Component
public class CurrentCustomerArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentCustomer.class);
    }

    @Override
    public LoginCustomer resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String token = JWTUtil.getHeaderToken(request);
        if(StringUtils.isEmpty(token))return null;

        CustomerTokenInfo customerTokenInfo = JWTUtil.verify(token);
        if(customerTokenInfo.getCustomerId() == null) return null;

        LoginCustomer loginCustomer = new LoginCustomer();
        loginCustomer.setCustomerId(customerTokenInfo.getCustomerId());
        loginCustomer.setNickname(customerTokenInfo.getNickname());
        return loginCustomer;
    }
}
